from django.shortcuts import render
from django.views.generic import TemplateView, FormView, DetailView, ListView

from .forms import CreateUserForm,CommentsForm
from user.models import User
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from .models import NewsDetail, NewsComments, NewsTag
from django.db.models import Q
# Create your views here.

#将访问index.html文件，并从数据库中获取modles中NewsDail的信息，展示在网站上
class NewsIndex(TemplateView):

    template_name = 'news/index.html'

    def get_context_data(self, **kwargs):
        news_info_0 = NewsDetail.objects.all().order_by('-add_time')[0:4]
        news_info_1 = NewsDetail.objects.all().order_by('-add_time')[0:2]
        news_info_2 = NewsDetail.objects.all().order_by('-add_time')[2:4]
        news_info_3 = NewsDetail.objects.all().order_by('-add_time')[4:6]
        news_info_4 = NewsDetail.objects.all().order_by('-add_time')[6:8]
        news_info_all = NewsDetail.objects.all() .order_by('-add_time')
        data = dict(news_info_0=news_info_0,
                    news_info_1=news_info_1,
                    news_info_2=news_info_2,
                    news_info_3=news_info_3,
                    news_info_4=news_info_4,
                    news_info_all=news_info_all,
                    )
        return super().get_context_data(**data)

#表单类,将django创建的表单传递过来的信息验证，验证成功则显示成功信息，不成功则表单仍然存在
class NewsLogin(FormView):

    template_name = 'news/login.html'
    form_class = CreateUserForm

    def get_context_data(self, **kwargs):
        '''获取表单信息'''
        data = dict(user_register=CreateUserForm(),
                    )
        return super().get_context_data(**data)

    def form_valid(self, form):
        '''验证表单用户信息'''
        data = form.cleaned_data
        user = authenticate(**data)
        if user:
            login(self.request, user)
        return super().form_valid(form)

    def get_success_url(self):
        '''成功则在当前页面显示成功信息'''
        url = self.request.META['HTTP_REFERER']
        return url


def user_logout(request):
    '''用户注销的方法'''
    logout(request)
    url = 'news/index/'
    return HttpResponseRedirect(url)


#点击网页contact us 按钮，跳转至contact.html
class NewsContact(TemplateView):
    template_name = 'news/contact.html'


#新闻分类实现
class NewsCategory(TemplateView):
    template_name = 'news/category.html'

    def get_context_data(self, **kwargs):
        '''获取新闻标签的信息在网站展示'''
        category = NewsTag.objects.all()
        data = dict(category=category)
        return super().get_context_data(**data)


#获取新闻分类中的新闻内容进行展示
class NewsCategoryList(ListView):
    model = NewsDetail
    template_name = 'news/category.html'

    def get_context_data(self, **kwargs):
        '''获取该类的新闻信息，并将信息传递至前端展示'''
        name = self.kwargs.get('name')
        news_info= NewsDetail.objects.all().order_by('-add_time')
        category = NewsTag.objects.all()
        category_result = NewsDetail.objects.filter(tag__name=name)
        data = dict(news_info=news_info,
                    category_result=category_result,
                    category=category)
        return super().get_context_data(**data)


#访问搜索页面
class NewsSearch(TemplateView):
    template_name = 'news/search.html'

#访问events页面，展示新闻图片
class NewsEvents(TemplateView):
    template_name = 'news/events.html'

    def get_context_data(self, **kwargs):
        '''获取从数据库获取所需的新闻信息'''
        news_info_5 = NewsDetail.objects.all().order_by('-add_time')[0:9]
        data=dict(news_info_5=news_info_5,
                  )
        return super().get_context_data(**data)


#完成用户注册的类
class NewsRegister(FormView):
    template_name = 'news/register.html'
    form_class = CreateUserForm

    def get_context_data(self, **kwargs):
        '''获取表单信息，展示表单'''
        data = dict(user_register=CreateUserForm(),
                    )
        return super().get_context_data(**data)

    def form_valid(self, form):
        '''验证表单信息'''
        data = form.cleaned_data
        try:
            User.objects.create_user(**data)
        except Exception:
            url = self.request.META['HTTP_REFERER']
            return HttpResponseRedirect(url)
        return super().form_valid(form)

    def get_success_url(self):
        '''成功注册后跳转的url'''
        url = 'news/index/'
        return url


#在新闻详情页展示新闻信息
class NewsDetailView(DetailView):
    model = NewsDetail
    template_name = 'news/single.html'
    context_object_name = 'news_detail'

    def get_context_data(self, **kwargs):
        '''获取新闻，及其与用户评论关联的信息'''
        comments_info = NewsComments.objects.filter(news_id=self.kwargs.get('pk')).order_by('-add_time')
        detail_info = NewsDetail.objects.filter(id=self.kwargs.get('pk'))[0]
        data = dict(comment_form=CommentsForm(),
                    comments_info=comments_info,
                    detail_info=detail_info,
                    )
        return super().get_context_data(**data)


#将该用户评论的新闻的评论信息存入数据库中
class NewsCommentsView(FormView):
    form_class = CommentsForm

    def form_valid(self, form):
        '''
        comments：获取评论信息
        user:获取用户的信息
        news_id:获取新闻数据库中的id
        评论不成功留在该页面
        '''
        url = self.request.META['HTTP_REFERER']
        comments = form.cleaned_data['comments']
        user = self.request.user
        news_id = self.request.POST.get('news_id', None)
        try:
            news = NewsDetail.objects.filter(id=news_id)[0]
            NewsComments.objects.create(user=user, news=news, comments=comments)
        except Exception:
            return HttpResponseRedirect(url)
        return super().form_valid(form)

    def get_success_url(self):
        '''成功后留在该页面'''
        return self.request.META['HTTP_REFERER']


#访问搜索页面，并从数据库中查找搜索的新闻，搜索新闻标题与内容相关的关键词信息
class NewsSearchView(ListView):
    model = NewsDetail
    template_name = 'news/search.html'

    # def get_queryset(self):
    #     search = self.request.GET.get('search', None)
    #     query = NewsDetail.objects.filter(Q(title__contains=search)|Q(content__contains=search))
    #     return query

    def get_context_data(self, **kwargs):
        '''
        search:获取关键词
        news_search:在获取的相关新闻信息
        '''
        search = self.request.GET.get('search', None)
        news_search = NewsDetail.objects.filter(Q(title__contains=search)|Q(content__contains=search))
        data = dict(news_search=news_search,
                    search=search)
        return super().get_context_data(**data)
